/**
 * Created by jocky on 30/08/2017.
 */
var smsObj = {
    controller: '',
    timer: 0,
    timeCount: 0,
    waitSeconds: 60
};

/**
 * 按钮显示的倒计时
 * @param dom
 */
function smsCounter(dom) {
    var limit = smsObj.waitSeconds - smsObj.timeCount;
    if (limit <= 0) {
        if (smsObj.timer) clearInterval(smsObj.timer);
        dom.removeAttr('disabled');
        dom.html("发送短信");
    } else {
        dom.html(limit + "秒后重发");
    }
    smsObj.timeCount++;
}

/**
 * 发送手机短信
 * @type int 1注册，4找回密码，5绑定手机号码，7修改安全码 6发送注册信息
 */
function sendSms(type) {
    if (smsObj.timer) clearInterval(smsObj.timer);
    smsObj.timeCount = 0;
    var dom = $('#form' + type);
    var params = {};
    switch (type) {
        case 1://注册账户
            smsObj.controller = "reg";
            var captcha = dom.find("input[name=captcha]").val();
            if (captcha == "") {
                setNotify('请输入图片验证码', true);
                return false;
            }
            params = {smsType: type, captcha: captcha};
            break;
        case 4://修改密码
            smsObj.controller = "password";
            var captcha = dom.find("input[name=captcha]").val();
            if (captcha == "") {
                setNotify('请输入图片验证码', true);
                return false;
            }
            params = {smsType: type, captcha: captcha};
            break;
        case 5://绑定手机号码
            smsObj.controller = "user";
            params = {smsType: type};
            break;
        case 6://发送注册信息
            smsObj.controller = "user";
            params = {smsType: type};
            break;
        case 7://7修改安全码
            smsObj.controller = "user";
            params = {smsType: type};
            break;
    }

    //有些类别直接查找绑定的手机号码
    var cellphoneDom = dom.find("input[name=cellphone]");
    if (cellphoneDom.length != 0) {
        var cellphone = cellphoneDom.val();
        if (!/^1[34578][0-9]{9}$/i.test(cellphone)) {
            setNotify('请输入正确的手机号码', true);
            return false;
        }
        params.cellphone = cellphone;
    }

    //disable the send sms button
    var buttonObj = dom.find("button[name=sendSmsBtn]");
    buttonObj.attr({disabled: true});

    $.getJSON("/" + smsObj.controller + "/send-sms", params, function (json) {
        if (json.code == 1) {
            //发送成功
            smsCounter(buttonObj);
            smsObj.timer = setInterval(function () {
                smsCounter(buttonObj);
            }, 1000);
        } else {
            if (type == 1 || type == 4) {
                refreshCaptcha(type);
            }
            //发送失败
            buttonObj.removeAttr('disabled');
            buttonObj.html("发送短信");
            setNotify(json.msg, true);

        }
    });
}